package com.hujia.hjsurprisemeal.repository;

import com.hujia.hjsurprisemeal.model.User;
import com.hujia.hjsurprisemeal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int addUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }

    @Override
    public User getUserById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public int updateUser(String username, User user) {
        return 0;
    }

    @Override
    public User getUserByName(String name) {
        return userMapper.selectByUsername(name);
    }

    @Override
    public User findByName(String name) {
        return null;
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public int deleteUser(int id) {
        return userMapper.deleteById(id);
    }
    @Override
    public User register(String username, String email, String password) {
        // 检查用户名是否已存在
//        User existingUser = userMapper.selectByUsername(username);
//        if (existingUser != null) {
//            throw new RuntimeException("用户名已存在");
//        }
        // 插入用户信息到数据库
        User user = new User();
        user.setName(username);
        user.setEmail(email);
        user.setPassword(password);
        user.setPoints(0);  // 初始化积分为 0
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        userMapper.insert(user);

        // 返回新注册的用户信息
        return user;
    }
    // 新增方法，通过ID更新用户信息
    public boolean updateUser(Long userId, String name, String email, String password) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false; // 用户不存在
        }
        // 更新用户信息
        user.setName(name);
        user.setEmail(email);
        user.setPassword(password);
        return userMapper.updateById(user) > 0; // 返回更新是否成功
    }

}